<template>
  <div class='params_container'>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>分类参数</el-breadcrumb-item>
    </el-breadcrumb>

    <el-card>
      <el-alert title="注意: 只允许为第三级分类设置相关参数!" type="warning" show-icon :closable="false"></el-alert>
      <el-row class="cat_opt">
        <el-col>
          <span>选择商品分类:</span>
          <el-cascader v-model="selectedCateKeys" :options="cateList" expand-trigger="hover" :props="cascaderProps"
            @change="handleChange" change-on-select clearable>
          </el-cascader>
        </el-col>
      </el-row>

      <el-tabs v-model="activeName" @tab-click="handleTabClick">
        <el-tab-pane label="动态参数" name="many">
          <el-button type="primary" size="small" :disabled="isBtnDisable" @click="addDialogVisible = true">添加参数
          </el-button>
          <el-table :data="manyTableData" border>
            <el-table-column type="expand">
              <template scope="{ row }">
                <el-tag v-for="(item,i) in row.attr_vals" :key="i" closable  @close="handleClose(i, row)">{{ item }}</el-tag>
                <el-input class="input-new-tag" v-if="row.inputVisible" v-model="row.inputValue" ref="saveTagInput" size="small"
                @keyup.enter.native="handleInputConfirm(row)" @blur="handleInputConfirm(row)">
                </el-input>
                <el-button v-else class="button-new-tag" size="small" @click="showInput(row)">+ New Tag</el-button>

              </template>
            </el-table-column>
            <el-table-column type="index" label="#"></el-table-column>
            <el-table-column prop="attr_name" label="参数名称"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="{ row }">
                <el-button class="el-icon-edit" size="mini" type="primary" @click="showEditDialog(row.attr_id)">编辑
                </el-button>
                <el-button class="el-icon-delete" size="mini" type="danger" @click="delParams(row.attr_id)">删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="静态属性" name="only">
          <el-button type="primary" size="small" :disabled="isBtnDisable" @click="addDialogVisible = true">添加属性
          </el-button>
          <el-table :data="onlyTableData" border>
            <el-table-column type="expand">
              <template scope="{ row }">
                <el-tag v-for="(item,i) in row.attr_vals" :key="i" closable  @close="handleClose(i, row)">{{ item }}</el-tag>
                <el-input class="input-new-tag" v-if="row.inputVisible" v-model="row.inputValue" ref="saveTagInput" size="small"
                  @keyup.enter.native="handleInputConfirm(row)" @blur="handleInputConfirm(row)">
                </el-input>
                <el-button v-else class="button-new-tag" size="small" @click="showInput(row)">+ New Tag</el-button>
              </template>
            </el-table-column>
            <el-table-column type="index" label="#"></el-table-column>
            <el-table-column prop="attr_name" label="参数名称"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="{ row }">
                <el-button class="el-icon-edit" size="mini" type="primary" @click="showEditDialog(row.attr_id)">编辑
                </el-button>
                <el-button class="el-icon-delete" size="mini" type="danger" @click="delParams(row.attr_id)">删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>

    <el-dialog :title="'添加' + titleText" :visible.sync="addDialogVisible" width="50%" @close="addDialogClosed">
      <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="100px">
        <el-form-item :label="titleText" prop="attr_name">
          <el-input v-model="addForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addParams">确 定</el-button>
      </span>
    </el-dialog>

    <el-dialog :title="'修改' + titleText" :visible.sync="editDialogVisible" width="50%" @close="editDialogClosed">
      <el-form :model="editForm" :rules="editFormRules" ref="editFormRef" label-width="100px">
        <el-form-item :label="titleText" prop="attr_name">
          <el-input v-model="editForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editParams">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import goods from '@/api/goods'

export default {
  name: 'MyParams',
  data () {
    return {
      cateList: [],
      cascaderProps: {
        value: 'cat_id',
        label: 'cat_name',
        children: 'children'
      },
      selectedCateKeys: [],
      activeName: 'many',
      manyTableData: [],
      onlyTableData: [],
      addDialogVisible: false,
      editDialogVisible: false,
      addForm: {
        attr_name: ''
      },
      editForm: {
        attr_name: ''
      },
      addFormRules: {
        attr_name: [{ required: true, message: '请输入参数名称', trigger: 'blur' }]
      },
      editFormRules: {
        attr_name: [{ required: true, message: '请输入参数名称', trigger: 'blur' }]
      }
    }
  },
  components: {
  },
  methods: {
    // 1.获取商品分类
    async getCateList () {
      const { data: res } = await goods.getCategories({})
      if (res.meta.status === 200) {
        this.cateList = res.data
      } else {
        this.$message.error(res.meta.msg)
      }
    },

    // 2.处理级联选择框改变
    async handleChange () {
      const len = this.selectedCateKeys.length
      // 不是三级分类
      if (len !== 3) {
        this.selectedCateKeys = []
        this.manyTableData = []
        this.onlyTableData = []
        return this.$message.error('请选择三级分类!')
      }
      this.getParamsList()
    },

    // 3.tab页签点击事件
    handleTabClick () {
      if (this.selectedCateKeys.length !== 3) {
        return this.$message.error('请先选择商品分类!')
      }
      this.getParamsList()
    },

    // 4.获取参数列表
    async getParamsList () {
      const { data: res } = await goods.getParamList(this.cateId, this.activeName)
      if (res.meta.status === 200) {
        res.data.forEach(item => {
          item.attr_vals = item.attr_vals ? item.attr_vals.split(' ') : []
          item.inputVisible = false
          item.inputValue = ''
        })
        if (this.activeName === 'many') {
          this.manyTableData = res.data
        } else {
          this.onlyTableData = res.data
        }
      } else {
        return this.$message.error(res.meta.msg)
      }
    },

    // 5.监听添加对话框关闭
    addDialogClosed () {
      this.$refs.addFormRef.resetFields()
    },

    // 6.确认添加参数
    addParams () {
      this.$refs.addFormRef.validate(async valid => {
        if (valid) {
          const { data: res } = await goods.addAttribute(this.cateId, this.addForm.attr_name, this.activeName)
          if (res.meta.status === 201) {
            this.addDialogVisible = false
            this.getParamsList()
            this.$message.success(res.meta.msg)
          } else {
            return this.$message.success(res.meta.msg)
          }
        } else {
          return false
        }
      })
    },

    // 7.点击按钮,展示修改的对话框
    async showEditDialog (attr_id) {
      const { data: res } = await goods.getAttributeById(this.cateId, attr_id, this.activeName)
      if (res.meta.status === 200) {
        this.editForm = res.data
      } else {
        return this.$message.error(res.meta.msg)
      }
      this.editDialogVisible = true
    },

    // 8.监听编辑对话框关闭
    editDialogClosed () {
      this.$refs.editFormRef.resetFields()
    },

    // 9.确认修改参数
    editParams () {
      this.$refs.editFormRef.validate(async valid => {
        if (valid) {
          const { data: res } = await goods.updateAttribute(this.cateId, this.editForm.attr_id, this.editForm.attr_name, this.activeName)
          if (res.meta.status === 200) {
            this.editDialogVisible = false
            this.getParamsList()
            this.$message.success(res.meta.msg)
          } else {
            this.$message.error(res.meta.msg)
          }
        } else {
          return false
        }
      })
    },

    // 10.删除参数
    delParams (attr_id) {
      this.$confirm('是否永久删除该参数?', '提示', { type: 'warning' }).then(async () => {
        const { data: res } = await goods.deleteAttribute(this.cateId, attr_id)
        if (res.meta.status === 200) {
          this.getParamsList()
          this.$message.success(res.meta.msg)
        } else {
          this.$message.error(res.meta.msg)
        }
      }).catch(() => { })
    },

    // 11.编辑文本框,失去焦点或按下
    async handleInputConfirm (row) {
      if (row.inputValue.trim().length === 0) {
        row.inputValue = ''
        row.inputVisible = false
        return
      }
      // 输入了内容,进一步处理
      row.attr_vals.push(row.inputValue)
      row.inputValue = ''
      // 将数据保存到数据库
      const { data: res } = await goods.addAttributes(this.cateId, row.attr_id, row.attr_name, this.activeName, row.attr_vals.join(' '))
      if (res.meta.status === 200) {
        this.$message.success(res.meta.msg)
      } else {
        this.$message.error(res.meta.msg)
      }
    },

    // 12.点击按钮，显示文本框
    showInput (row) {
      row.inputVisible = true
      // $nextTick 重新渲染后才执行
      this.$nextTick(_ => {
        this.$refs.saveTagInput.focus()
      })
    },

    // 13.删除对应的参数可选值
    async handleClose (i, row) {
      row.attr_vals.splice(i, 1)
      const { data: res } = await goods.addAttributes(this.cateId, row.attr_id, row.attr_name, this.activeName, row.attr_vals.join(' '))
      if (res.meta.status === 200) {
        this.$message.success('删除成功')
      } else {
        this.$message.error(res.meta.msg)
      }
    }

  },
  computed: {
    // 按钮是否禁用
    isBtnDisable () {
      return this.selectedCateKeys.length !== 3
    },
    // 获取当前三级分类的id
    cateId () {
      if (this.selectedCateKeys.length === 3) {
        return this.selectedCateKeys[2]
      } else {
        return null
      }
    },
    // 动态计算标题的文本
    titleText () {
      if (this.activeName === 'many') {
        return '动态参数'
      }
      return '静态属性'
    }
  },
  created () {
    this.getCateList()
  },
  mounted () {
  }
}
</script>

<style lang='less' scoped>
.el-breadcrumb {
  line-height: 50px;
}

.cat_opt {
  margin: 15px 0;
}

.el-cascader {
  width: 20%;
  margin-left: 15px;
}

.el-table {
  margin-top: 15px;
}

/deep/ .el-table__expanded-cell {
  padding: 20px 50px;

  .el-tag {
    margin-right: 15px;
  }
}

.input-new-tag {
  width: 120px;
}
</style>
